from django import http
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import render, redirect
# Create your views here.
from django.urls import reverse
from django.views import View
from apps.oauth.models import OAuthQQUser
from utils.response_code import RETCODE
from QQLoginTool.QQtool import OAuthQQ

# 4.判断openid是否绑定的函数封装
def is_bind_openid(openid, request):

    # 判断openid是不是已经在表中存在
    try:
        qq_user = OAuthQQUser.objects.get(openid = openid)
    except OAuthQQUser.DoesNotExist:
        # 不存在————绑定页进行绑定
        context = {'openid':openid}
        response = render(request, 'oauth_callback.html', context)
    else:
        # 存在
        user = qq_user.user
        # 1.保持登录状态
        login(request, user, )
        # 2.cookie保存用户名返回主页
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', user.username, max_age=14*2*24*3600)
        # 3.重定向到首页

    return  response
# qq成功登录之后的回调函数
class QQOauthCallbackView(View):
    def get(self, request):
        # 1. code request.GET.get获取数据
        code = request.GET.get('code')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=None)
        # 2. code---acess_token 根据数据获取
        token = oauth.get_access_token(code)
        # 3. acess_token --- openid  然后再获取openid
        openid = oauth.get_open_id(token)

        # 4.判断openid是否绑定
        response = is_bind_openid(openid, request)

        return response

class QQLoginView(View):
    # qq的登录网址
    def get(self,request):
        # 1导包 qq登录工具f
        # 2.实例化对象，获取需要的参数
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=None)
        # 3.获取qq登录地址，返回给前端js的
        login_url = oauth.get_qq_url()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url': login_url})
        # pass